<template>
  <div class="CeDianbos">
    <div class="leftbox">
      <TreeList @nodeClick="nodeClick" @checktype="checktype"></TreeList>
    </div>
    <div class="rightbox">
      <div class="righttop">
        <span class="time" >时间</span>
              <span >
                <el-date-picker
                  size="small"
                  style="margin-right: 20px;"
                  v-model="value1"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </span>
              <span>
                <el-button  type="primary" size="small" @click="getdatalist">查询</el-button>
                <el-button  type="primary" size="small" @click="shanchu(false)">执行删除</el-button>
              </span>
      </div>
      <div class="rightbody" ref="rightbody">
        <div ref="getheight">
          <div>
            <el-button type="primary" size="small" @click="quanxuan">全选</el-button>
            <el-button type="primary" size="small" @click="quanbuxuan">全不选</el-button>
          </div>
          <div class="checkboxs" >
            <el-empty v-if="!checklist.length" :image-size="30" description="暂无测点数据"></el-empty>
            <el-checkbox-group v-model="checkedCities" @change="changecheck">
              <el-checkbox v-for="(item,index) in checklist" :label="item.itemTag" :key="index">{{item.itemName}}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="title">
            <div>测点数据处理</div>
            <div class="butexp">
              <!-- <el-button type="primary" size="small" >导出模版</el-button> -->
              <el-button type="primary" size="small" class="moban" @click="dialogupload=true">数据导入</el-button>
              <TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile>
            </div>
            <el-dialog
              title="导入文件"
              :visible.sync="dialogupload"
              width="30%">
              <div>
                <el-upload
                  class="upload-demo"
                  drag
                  :on-change="handleChange"
                  :file-list="fileList"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  multiple>
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="importcancel">取 消</el-button>
                <el-button size="small" type="primary" @click="sureumport">确 定</el-button>
              </span>
            </el-dialog>
          </div>
        </div>
        <div class="table" :style="{height:tableheight+'px'}">
            <el-table
            :size="issize"
            border
            :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
            v-loading="loading"
            height="calc(100% - 0px)"
            ref="table"
            style="width: 100%"
            :data="tableData">
            <template slot="empty" >
              <el-empty description="暂无数据" :image-size="150"></el-empty>
            </template>
            <el-table-column
              type="index"
              label="序号"
              v-if="tableData.length"
              align="center"
              fixed
              width="80">
            </el-table-column>
            <el-table-column
              prop="deviceName"
              v-if="tableData.length"
              fixed
              label="设备名称">
            </el-table-column>
            <el-table-column
              prop="time"
              v-if="tableData.length"
              fixed
              :width="tableData.length?'170':''"
              align="center"
              label="时间">
            </el-table-column>
            <el-table-column
              v-for="(item,index) in columnlist"
              :key="index"
              :prop="item.prop"
              align="right"
              width="120"
              :label="item.label">
            </el-table-column>
            <el-table-column
              fixed="right"
              width="120"
              align="center"
              v-if="tableData.length"
              label="操作">
              <template #default="{row}">
                <div>
                  <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                    <i @click="xiugai(row)"  class="el-icon-edit" style="color:#1a90fe ;margin-right: 10px; cursor: pointer;"></i>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <i @click="shanchu(row)"  class="el-icon-delete" style="color: red;cursor: pointer;margin-right: 10px;"></i>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageNo"
            :page-size="20"
            @current-change="getdatalist"
            :total="+totalCount">
          </el-pagination>
        </div>
      </div>
      <!-- dialog弹窗 -->
       <div>
        <el-dialog
          title="测点数据编辑"
          :visible.sync="dialogVisible"
          width="50%">
          <div>
            <el-form ref="form" :model="form" label-width="120px">
                <el-col :span="12">
                  <el-form-item label="设备名称">
                    <el-input v-model="form.deviceName" placeholder="请输入设备名称" size="small"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="数据时间">
                    <el-input v-model="form.time" placeholder="请输入数据时间" size="small"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-for="(item,index) in pointslist" :key="index">
                  <el-form-item :label="item.itemName">
                    <el-input v-model="item.itemData" placeholder="请输入数据值" size="small"></el-input>
                  </el-form-item>
                </el-col>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="quxiao" size="small">取 消</el-button>
            <el-button type="primary" @click="submit" size="small">确 定</el-button>
          </div>
        </el-dialog>
       </div>
    </div>
  </div>
</template>

<script>
import {exportexcel} from '@/utils/excel'
import {getcedianlistapi,postundatelistapi,postdeletelistapi,postImportListapi} from '@/api/system/DataProcessing'
import TopTile from '@/components/TopTitle/index.vue'
import {ceshijiekouapi} from '@/api/monitor'
import TreeList from './components/TreeList'
export default {
  name: 'CallPoliceCeDian',
  components: {
    TreeList,
    TopTile
  },
  data() {
    return {
      dialogVisible:false,
      issize: 'medium',
      form:{},
      loading:false,
      value1: [],
      checklist: [],
      tableData:[],
      checkedCities: [],
      treevalue: {},
      columnlist:[],
      pointslist: [],
      tableheight:'',
      pageNo: 0,
      totalCount:'',
      isFirstTrigger:true,
      dialogupload:false,
      fileList:[],
      formfile:{}
    };
  },

  mounted() {
    this.gettime()
  },

  methods: {
    // 树节点点击
    async nodeClick(val) {
      this.treevalue=val
      await this.getlista(val)
      if (!this.checkedCities.length) {
        this.checktype()
      } else {
        this.getdatalist()
      }
    },
    async sureumport(){
      const formData = new FormData();
      formData.append('file', this.formfile);
      formData.append('deviceId', this.treevalue.id);
      const res=await postImportListapi(formData)
      this.$message({
        type:res.code==200?'success':'warning',message:res.message
      })
      if(res.code==200)this.importcancel()
      if(res.code==200)this.getdatalist()
    },
    async handleChange(val,file){
      this.fileList=file.slice(-1)
      this.formfile = val.raw
    },
    importcancel(){
      this.fileList=[]
      this.formfile={}
      this.dialogupload=false
    },
    // 获取列表数据
    async getdatalist() {
      if (!this.treevalue.id) return this.$message.warning('请先选择企业')
      if (!this.checkedCities.length) return this.$message.warning('请先选择测点标识')
      this.loading=true
      const { data: { list,totalCount      } } = await getcedianlistapi({
        pageNo:this.pageNo-1<0?0:this.pageNo-1,pageSize:20,
        deviceId:this.treevalue.id,startDate:this.value1[0],endDate:this.value1[1],itemTags:this.checkedCities.join(',')
      })
      this.totalCount=totalCount
      // 处理表格数据
      const array= list.map(ele => {
        ele.points.forEach(item => {
          item['itemName']=this.checklist.find(ele => ele.itemTag == item.itemTag).itemName,
          ele[item.itemTag]=item.itemData
        })
        return ele
      });
      this.tableData = array
      // 处理表头数据
      this.columnlist =[]
      for (let i = 0; i < array.length; i++) { 
        if (array[i].points.length) {
          array[i].points.map(item => {
            this.columnlist.push({
              label: item.itemName,
              prop:item.itemTag
            })
          })
          break
        }
      }
      this.loading=false
    },
    // 确认修改
    async submit() {
      const itemData=this.pointslist.map(ele=>ele.itemData)
      const itemTag=this.pointslist.map(ele=>ele.itemTag)
      await postundatelistapi({
        deviceId: this.treevalue.id,itemData:itemData.join(','),
        time:this.form.time,itemTag:itemTag.join(',')
      }).then(res => {
        this.$message({
          type:res.code=='200'?'success':'warning',
          message:res.code=='200'?'修改成功':res.message
        })
      })
      this.quxiao()
      this.getdatalist()
    },
    // 弹窗取消
    quxiao() {
      this.dialogVisible = false
      this.form = {}
      this.pointslist=[]
    },
    changecheck(){
      this.$forceUpdate()
    },
    // 修改
    xiugai(row) {
      this.pointslist = row.points
      this.$set(this.form,'deviceName',row.deviceName)
      this.$set(this.form,'time',row.time)
      this.dialogVisible=true
    },
    // 删除
    shanchu(row) {
      this.$confirm(`此操作将删除该${!row?'设备下所选时间段及所选测点下的所有数据':'时间段下的数据'}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await postdeletelistapi({
            deviceId: this.treevalue.id, itemTags: this.checkedCities.join(','),
            startDate:!row?this.value1[0]:row.time, endDate:!row?this.value1[1]:row.time
          })
            this.$message({
              type: res.code == 200 ? 'success' : 'warning',
              message:res.code == 200 ?'删除成功':res.message
            })
            this.getdatalist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    checktype() {
      this.tableData = []
      this.columnlist = []
      this.checklist=[]
    },
    // 获取测点数据
    async getlista(val){
      const {data:{list}} = await ceshijiekouapi({ deviceId: val.id })
      this.checklist =[]
      list.map(ele => {
        ele.itemDataViews.map((item,index) => {
          this.checklist.push(item)
        })
      })
      this.checklist = this.checklist.filter(ele => ele.dataType !== 'YX')
      this.$nextTick(() => {
        this.tableheight = this.$refs.rightbody.clientHeight - this.$refs.getheight.clientHeight - 90
        this.$refs['table'].doLayout()
      })
      this.checkedCities=this.checklist.map(ele=>ele.itemTag)
    },
    // 全选
    quanxuan() {
      this.checkedCities=this.checklist.map(ele=>ele.itemTag)
    },
    // 全不选
    quanbuxuan() {
      this.checkedCities=[]
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      if (!this.treevalue.id) return this.$message.warning('请先选择企业')
      const itemTagNames = this.checklist.map(ele => {
        const arr=[]
        this.checkedCities.map(item => {
          if (item == ele.itemTag) {
            arr.push(ele.itemName)
          }
        })
        return arr
      })
      exportexcel('sst-microservice-biz/sst/measure/points/data/export',{
        deviceId: this.treevalue.id, startDate: this.value1[0], endDate: this.value1[1], itemTags: this.checkedCities.join(','),
        itemTagNames:itemTagNames.join(',')
      },'测点数据处理')
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
    },
    // 获取当前时间戳
    gettime() {
      this.value1=[]
      // 获取今天的时间戳
      const today = new Date();
      const todayTimestamp = today.setHours(0, 0, 0, 0);
      // 获取明天的时间戳
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      const tomorrowTimestamp = tomorrow.setHours(0, 0, 0, 0);
      // 格式化时间戳为yyyy-MM-dd
      const formatDate = (timestamp) => {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };
      this.value1.push(formatDate(todayTimestamp));
      this.value1.push(formatDate(tomorrowTimestamp));
    },
  },
  watch: {
    value1: {
      deep:true,
      handler(val) {
        if (this.isFirstTrigger) {
          this.isFirstTrigger = false;
          return;
        }
        this.pageNo = 0;
        this.getdatalist();
      }
    }
  },
  beforeUpdate() {
    this.$nextTick(() => {
      this.$refs['table'].doLayout()
    })
  }
};
</script>

<style scoped lang="scss">
.CeDianbos{
  height: 100%;
  display: flex;
  .leftbox{
    width: 300px;
    padding: 20px;
    background-color: #fff;
  }
  .rightbox{
    width: calc(100% - 310px);
    height: 100%;
    margin-left: 10px;
    overflow: auto;
     .righttop{
      height: 80px;
      background-color: #fff;
      line-height: 80px;
      padding: 0 20px;
      margin-bottom: 10px;
      .time{
        margin: 0 15px;
        font-size: 14px;
        color: #606266;
       }
    }
    .rightbody{
      padding: 20px;
      background-color: #fff;
      height: calc(100% - 90px);
      overflow-y: auto;
      /* display: flex;
      flex-direction: column; */

      .checkboxs{
        margin: 10px 0;
      }
      .title{
        margin-bottom: 10px;
        display:flex;
        justify-content:space-between;
        .butexp{
          display: flex;
          .moban{
            margin-right: 10px;
          }
        }
      }
      .fenye{
        margin-top: 5px;
        text-align: right;
      }
    }
  }
}

::v-deep .el-checkbox{
  margin-bottom: 10px;
  margin-right: 0;
  width: calc(100% / 8);
}
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .upload-demo{
  width: 100%;
  text-align: center;
}
</style>